var delay,
    index = 0,
    timer,
    score,
    name = '',
    time = 0,
    question = ['1短','2短','1长1短','1长2短','1长9短','不断的长声响','不断的短声响','重复短声响','无声音无显示','5短','8短','1长3短','1长8短'],
    answer = ['系统正常启动','常规错误','内存或主板错误','显卡或显示器错误','主板BIOS损坏','内存问题','电源、显示器或显卡未连接','电源故障','电源故障','CPU错误','显卡错误','内存错误','显卡测试错误'],
    questionArr = [],
    answerArr = [],
    result = [];

function init(){
    while(!name){
        name = prompt('请输入姓名：') || '';
        $('.name').text(name);
    }
    while(question.length > 0){
        let Random = Math.floor(Math.random() * question.length);
        questionArr.push(question.splice(Random,1)[0]);
        answerArr.push(answer.splice(Random,1)[0]);
    }
    timer = setInterval(()=> {
        time++;
        $('.time').text(time);
    }, 1000);
    update();
}

function update(){
    score = 0;
    for(let i = 0; i < result.length; i++){
        score = result[i] == answerArr[i] ? ++score : score;
    }
    $('.score').text(score);
    if(index >= questionArr.length - 1){ $('.buttonBox button').text('提交'); }
    if(index == questionArr.length){
        alert('测试结束！');
        clearInterval(timer);
        $.ajax({
            url: './php/save.php',
            type: 'POST',
            data: {
                name,
                time,
                score
            }
        })
        return false;
    } else if( index > questionArr.length){
        return false;
    } else {
        $('.title span').text(`第${index + 1}题`);
        $('.question').text(questionArr[index]);
        let temp = '', current = new Set();
        for(let i = current.size; i <= 4; i++){
            current.add(answerArr[i == 0?index:Math.floor(Math.random() * answerArr.length)]);
            i = current.size;
            temp = [...current].sort();
        }
        let i = 0;
        while(i < 4){
            $('.choise p').eq(i).children('label').text(temp[i]);
            i++;
        }
    }
}

$(".buttonBox button").click(() => {
    for(var i = 0; i < $('.choose').length; i++){
        if($('.choose')[i].checked){
            answer[index-1] = $(`.choose:eq(${i})`).data('id');
            ++index;
            $(`.choose`).get(i).checked = false;
            result.push($(`.choose`).eq(i).siblings('label').text());
            update();
        }
    }
});

init();